//
//  XPhotoBrowserCell.m
//  XPhotoLibraryKit
//
//  Created by Wu,Xinting on 2018/3/21.
//

#import "XPhotoBrowserCell.h"
#import "XPhoto.h"
#import "XPhotoVideoView.h"
#import <SVProgressHUD/SVProgressHUD.h>

@interface XPhotoBrowserCell ()

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) XPhotoVideoView *videoView;

@end

@implementation XPhotoBrowserCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.clipsToBounds = YES;
        [self.contentView addSubview:self.imageView];
        [self.contentView addSubview:self.videoView];
    }
    return self;
}

- (void)refresh {
    self.imageView.hidden = NO;
    self.imageView.frame = self.sourceRect;
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = NO;
    options.networkAccessAllowed = YES;
    options.progressHandler = ^(double progress, NSError * _Nullable error, BOOL * _Nonnull stop, NSDictionary * _Nullable info) {
        [SVProgressHUD showProgress:progress status:@"正在同步iCloud"];
    };
    [[PHImageManager defaultManager] requestImageDataForAsset:self.photo.asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        self.imageView.image = [UIImage imageWithData:imageData];
        [UIView animateWithDuration:0.3 animations:^{
            self.imageView.frame = [self fitRectForPhoto];
            self.backgroundColor = [UIColor blackColor];
        }];
        if ([SVProgressHUD isVisible]) {
            [SVProgressHUD showSuccessWithStatus:@"完成"];
            [SVProgressHUD dismissWithDelay:0.5];
        }
    }];
    
    if (self.photo.asset.mediaType == PHAssetMediaTypeVideo) {
        self.videoView.photo = self.photo;
        [self.videoView load];
        self.videoView.hidden = NO;
    } else {
        self.videoView.hidden = YES;
    }
}

- (void)closeAnimate:(void (^)(void))endBlock {
    [UIView animateWithDuration:0.2 animations:^{
        self.videoView.hidden = YES;
        self.backgroundColor = [UIColor clearColor];
        self.imageView.frame = self.targetRect;
    } completion:^(BOOL finished) {
        if (endBlock) {
            endBlock();
        }
    }];
}

- (void)updatePhoto:(BOOL)animated {
    if (!animated) {
        self.imageView.transform = self.photo.transform;
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            self.imageView.transform = self.photo.transform;
        }];
    }
}

- (void)endDisplay {
    self.photo.transform = CGAffineTransformIdentity;
    self.imageView.transform = self.photo.transform;
    self.imageView.hidden = NO;
    [self.videoView clean];
}

- (BOOL)shouldTranslate:(CGPoint)translate {
    if (translate.x > 0 && self.imageView.frame.origin.x >= 0) {
        return NO;
    } else if (translate.x < 0 && self.imageView.frame.origin.x + self.imageView.frame.size.width <= self.bounds.size.width) {
        return NO;
    }
    return YES;
}

- (void)prepareForReuse {
    [super prepareForReuse];
    
    self.backgroundColor = [UIColor clearColor];
    self.imageView.image = nil;
    [self.videoView clean];
}

- (void)checkPosition {
    CGAffineTransform correctTransform = self.photo.transform;
    CGFloat maxTranx = (self.imageView.bounds.size.width / 2.f * (correctTransform.a - 1.f));
    CGFloat maxTrany = (self.imageView.bounds.size.height / 2.f * (correctTransform.a - 1.f));
    correctTransform.tx = MIN(fabs(correctTransform.tx), maxTranx) * (correctTransform.tx / fabs(correctTransform.tx));
    correctTransform.ty = MIN(fabs(correctTransform.ty), maxTrany) * (correctTransform.ty / fabs(correctTransform.ty));
    
    if (!CGAffineTransformEqualToTransform(self.photo.transform, correctTransform)) {
        self.photo.transform = correctTransform;
        [UIView animateWithDuration:0.2 animations:^{
            self.imageView.transform = self.photo.transform;
        }];
    }
}

#pragma mark - Action
#pragma mark - Private
- (CGRect)fitRectForPhoto {
    CGRect rect = self.bounds;
    CGFloat fitHeight = ((float)self.photo.asset.pixelHeight / self.photo.asset.pixelWidth) * self.bounds.size.width;
    rect.size.height = fitHeight;
    rect.origin.y = (self.bounds.size.height - fitHeight) / 2.f;
    return rect;
}

#pragma mark - Get&Set
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _imageView;
}

- (XPhotoVideoView *)videoView {
    if (!_videoView) {
        _videoView = [[XPhotoVideoView alloc] initWithFrame:self.bounds];
    }
    return _videoView;
}

@end
